<template>
  <v-dialog v-model="dialogVisible" max-width="500px" persistent>
    <v-card>
      <v-card-title>
        {{ user ? '编辑用户信息' : '新建用户' }}
      </v-card-title>

      <v-card-text>
        <v-form ref="formRef" v-model="isValid">
          <v-text-field label="用户名" v-model="form.username" :rules="[rules.required]" required />

          <v-text-field
            label="邮箱"
            v-model="form.email"
            :rules="[rules.required, rules.email]"
            required
          />

          <v-text-field
            label="密码"
            v-model="form.password"
            type="password"
            hint="不填写表示不修改密码"
          />

          <v-select
            v-model="form.roles"
            :items="allRoles"
            item-title="description"
            item-value="name"
            label="权限选择"
            multiple
            chips
            clearable
          />
        </v-form>
      </v-card-text>

      <v-card-actions class="justify-end">
        <v-btn text @click="close">取消</v-btn>
        <v-btn color="primary" @click="submit" :disabled="!isValid">保存</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { getRoles } from '@/api/roles'
import { useMessageStore } from '@/stores/MessageStore'

import { ref, reactive, watch } from 'vue'

const props = defineProps({
  modelValue: Boolean,
  user: Object,
})
const emit = defineEmits(['update:modelValue', 'submit'])

// 对话框开关
const dialogVisible = ref(false)

// 表单状态
const isValid = ref(false)
const formRef = ref()

const allRoles = ref([])

const defaultAvatar = 'https://cdn.vuetifyjs.com/images/john.jpg'

const fetchRoles = async () => {
  try {
    const response = await getRoles()
    allRoles.value = response.data.map((role) => ({
      description: role.description,
      name: role.name,
      id: role.id,
    }))
  } catch {
    useMessageStore().trigger({
      text: '获取角色列表失败',
      color: 'error',
    })
  }
}

const form = reactive({
  id: null,
  username: '',
  email: '',
  roles: [],
  password: '',
  avatar: '',
  avatarFile: null,
})

const rules = {
  required: (v) => !!v || '此字段为必填',
  email: (v) => /.+@.+/.test(v) || '请输入有效的邮箱地址',
}

const submit = () => {
  formRef.value?.validate().then((success) => {
    if (success) {
      const selectedRoles = allRoles.value.filter((r) => form.roles.includes(r.name))
      emit('submit', { ...form, roles: selectedRoles })
      close()
    }
  })
}

const resetForm = () => {
  // 如果是新建用户，重置表单；否则填充用户信息
  if (props.user) {
    form.id = props.user.id || null
    form.username = props.user.username
    form.email = props.user.email
    form.password = ''
    form.avatar = props.user.avatar || defaultAvatar
    form.roles = props.user.roles.map((role) => role.name) // 保持一致性
    form.avatarFile = null
  } else {
    form.id = null
    form.username = ''
    form.email = ''
    form.password = ''
    form.avatar = defaultAvatar
    form.roles = []
    form.avatarFile = null
  }
}

const close = () => {
  dialogVisible.value = false
}

watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val
    if (val) {
      fetchRoles()
      resetForm()
    }
  },
)

watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})
</script>

<style scoped></style>
